"""
应用配置管理
支持从环境变量和配置文件加载设置
"""

import os
from typing import Optional
from pydantic import BaseModel


class TaskSchedulerSettings(BaseModel):
    """任务调度器配置"""

    # 服务器配置
    host: str = "0.0.0.0"
    port: int = 8001
    debug: bool = False

    # 工作协程配置
    light_workers: int = 3  # 轻度任务工作协程数量
    heavy_workers: int = 2  # 重度任务工作协程数量

    # 队列配置
    light_queue_maxsize: int = 500
    heavy_queue_maxsize: int = 100
    main_queue_maxsize: int = 1000

    # 任务执行配置
    default_timeout: int = 300  # 默认任务超时时间(秒)
    max_retries: int = 3  # 默认最大重试次数

    # 进程池配置
    process_pool_workers: Optional[int] = None

    # 存储配置
    storage_cleanup_interval: int = 3600  # 存储清理间隔(秒)
    storage_keep_completed: int = 500  # 保留的已完成任务数量

    # SSE配置
    sse_heartbeat_interval: int = 30  # SSE心跳间隔(秒)
    sse_max_queue_size: int = 100  # SSE客户端消息队列最大大小

    # 监控配置
    enable_monitoring: bool = True
    monitoring_interval: int = 60  # 监控统计间隔(秒)

    # 日志配置
    log_level: str = "INFO"
    log_file: Optional[str] = "logs/task_scheduler.log"
    log_rotation: str = "1 day"
    log_retention: str = "30 days"

    # 数据库配置（预留）
    database_url: Optional[str] = None
    redis_url: Optional[str] = None

    def __init__(self, **kwargs):
        # 从环境变量加载配置
        env_config = {
            "host": os.getenv("TASK_HOST", "0.0.0.0"),
            "port": int(os.getenv("TASK_PORT", "8001")),
            "debug": os.getenv("TASK_DEBUG", "false").lower() == "true",
            "light_workers": int(os.getenv("LIGHT_WORKERS", "3")),
            "heavy_workers": int(os.getenv("HEAVY_WORKERS", "2")),
            "light_queue_maxsize": int(os.getenv("LIGHT_QUEUE_MAXSIZE", "500")),
            "heavy_queue_maxsize": int(os.getenv("HEAVY_QUEUE_MAXSIZE", "100")),
            "main_queue_maxsize": int(os.getenv("MAIN_QUEUE_MAXSIZE", "1000")),
            "default_timeout": int(os.getenv("DEFAULT_TASK_TIMEOUT", "300")),
            "max_retries": int(os.getenv("MAX_RETRIES", "3")),
            "process_pool_workers": (
                int(os.getenv("PROCESS_POOL_WORKERS", "0"))
                if os.getenv("PROCESS_POOL_WORKERS")
                else None
            ),
            "storage_cleanup_interval": int(
                os.getenv("STORAGE_CLEANUP_INTERVAL", "3600")
            ),
            "storage_keep_completed": int(os.getenv("STORAGE_KEEP_COMPLETED", "500")),
            "sse_heartbeat_interval": int(os.getenv("SSE_HEARTBEAT_INTERVAL", "30")),
            "sse_max_queue_size": int(os.getenv("SSE_MAX_QUEUE_SIZE", "100")),
            "enable_monitoring": os.getenv("ENABLE_MONITORING", "true").lower()
            == "true",
            "monitoring_interval": int(os.getenv("MONITORING_INTERVAL", "60")),
            "log_level": os.getenv("LOG_LEVEL", "INFO"),
            "log_file": os.getenv("LOG_FILE", "logs/task_scheduler.log"),
            "log_rotation": os.getenv("LOG_ROTATION", "1 day"),
            "log_retention": os.getenv("LOG_RETENTION", "30 days"),
            "database_url": os.getenv("DATABASE_URL"),
            "redis_url": os.getenv("REDIS_URL"),
        }

        # 合并配置
        merged_config = {**env_config, **kwargs}
        super().__init__(**merged_config)

    def get_process_pool_workers(self) -> int:
        """获取进程池工作进程数量"""
        if self.process_pool_workers is not None:
            return self.process_pool_workers

        import multiprocessing

        return min(4, multiprocessing.cpu_count())


# 全局配置实例
settings = TaskSchedulerSettings()


def get_settings() -> TaskSchedulerSettings:
    """获取全局配置实例"""
    return settings


def update_settings(**kwargs) -> None:
    """更新配置"""
    global settings
    for key, value in kwargs.items():
        if hasattr(settings, key):
            setattr(settings, key, value)


# 配置验证函数
def validate_settings() -> None:
    """验证配置有效性"""
    if settings.light_workers < 1:
        raise ValueError("轻度任务工作协程数量必须大于0")

    if settings.heavy_workers < 1:
        raise ValueError("重度任务工作协程数量必须大于0")

    if settings.default_timeout < 1:
        raise ValueError("默认超时时间必须大于0")

    if settings.max_retries < 0:
        raise ValueError("最大重试次数不能小于0")

    print(f"配置验证通过:")
    print(f"  - 轻度工作协程: {settings.light_workers}")
    print(f"  - 重度工作协程: {settings.heavy_workers}")
    print(f"  - 进程池工作进程: {settings.get_process_pool_workers()}")
    print(f"  - 默认超时时间: {settings.default_timeout}秒")
